package com.duguo.dynamicmvc.factory.stage;

import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.duguo.dynamicmvc.factory.ControllerFactory;
import com.duguo.dynamicmvc.factory.WorkingModel;
import com.duguo.dynamicmvc.factory.processor.ProcessorHolder;
import com.duguo.dynamicmvc.factory.processor.register.RegisterProcessor;
import com.duguo.dynamicmvc.factory.processor.view.ViewProcessor;
import com.duguo.dynamicmvc.factory.utils.BeanUtils;
import com.duguo.dynamicmvc.view.View;

public class RegisterViewControllersStage implements Stage {
	
	private static final Log _log=LogFactory.getLog(RegisterViewControllersStage.class);

    public void execute(ControllerFactory controllerFactory) throws Exception {
        WorkingModel workingModel = controllerFactory.getWorkingModel();
        if(workingModel.isMultiActionController()) {
	        registerViewMapping(controllerFactory, workingModel);
	    }
    }

	private void registerViewMapping(ControllerFactory controllerFactory, WorkingModel workingModel) throws Exception {
		Object controllerInstance = workingModel.getControllerInstance();
		Map registedControllers=BeanUtils.getFieldValue(controllerInstance, "registedControllers", Map.class);
		ProcessorHolder processorHolder = controllerFactory.getControllerBuilder().getProcessorHolder();
		ViewProcessor viewProcessor = processorHolder.getViewProcessor();
		RegisterProcessor registerProcessor = processorHolder.getRegisterProcessor();
		String controllerPath = workingModel.getControllerPath();
		
		Map<String, Object> staticViewMapping = workingModel.getStaticViewMapping();
		for (String controllerName : staticViewMapping.keySet()) {
			if(registedControllers.containsKey(controllerName)){
				_log.warn(controllerName+" already exist, ignore the static view mapping entry");
				continue;
			}
			Object tempObj=staticViewMapping.get(controllerName);
			View view=null;
			if(tempObj instanceof String){
				view = viewProcessor.getViewByName(controllerPath, (String)tempObj,false);
			}else if(tempObj instanceof View){
				view= (View)tempObj;
			}else{
				throw new RuntimeException("unknown view:"+tempObj);
			}
			registerProcessor.registerControllerView(controllerInstance, controllerName, view);
		}
	}
}
